package com.shenke.ihgateway.blackfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.Map;

@Slf4j
public class BlackIpUtils {

    private static BitMapBloomFilter bloomFilter;

    // 判断 ip 是否在黑名单内
    public static boolean isBlackIp(String ip) {
        return bloomFilter != null && bloomFilter.contains(ip);
    }

    // 重建 ip 黑名单
    public static void rebuildBlackIp(String configInfo) {
        try {
            if (StrUtil.isBlank(configInfo)) {
                log.info("配置信息为空，使用默认空黑名单");
                configInfo = "{}";
            }
            // 解析 yaml 文件
            Yaml yaml = new Yaml();
            Map map = yaml.loadAs(configInfo, Map.class);
            // 获取 ip 黑名单
            List<String> blackIpList = (List<String>) map.get("blackIpList");
            // 加锁防止并发
            synchronized (BlackIpUtils.class) {
                if (CollectionUtil.isNotEmpty(blackIpList)) {
                    // 注意构造参数的设置
                    BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(1000);
                    for (String ip : blackIpList) {
                        bitMapBloomFilter.add(ip);
                    }
                    bloomFilter = bitMapBloomFilter;
                    log.info("成功加载黑名单IP列表，共{}个", blackIpList.size());
                } else {
                    bloomFilter = new BitMapBloomFilter(100);
                    log.info("黑名单IP列表为空");
                }
            }
        } catch (Exception e) {
            log.error("重建黑名单失败", e);
            // 确保bloomFilter不为空
            bloomFilter = new BitMapBloomFilter(100);
        }
    }
}
